package com.vjwealth.android.nos.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * projectName KNOS
 * date 2017/9/30
 * description com.vjwealth.android.nos.adapter
 */
abstract class RecyclerViewAdapter<T>(
        var context: Context,
        var layoutResId: Int,
        var dataList: List<T>) : RecyclerView.Adapter<RecyclerViewAdapter.CommonViewHolder>() {

    var mContext: Context
    var mInflater: LayoutInflater
    var mLayoutResId: Int
    var mDataList: List<T>

    var onItemClickListener: OnRecyclerViewItemClickListener<T>? = null

    init {
        mContext = context
        mInflater = LayoutInflater.from(context)
        mLayoutResId = layoutResId
        mDataList = dataList
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CommonViewHolder {
        var layoutId = mLayoutResId
        return CommonViewHolder(mInflater.inflate(layoutId, parent, false))
    }

    override fun onBindViewHolder(holder: CommonViewHolder?, position: Int, payloads: MutableList<Any>?) {
        super.onBindViewHolder(holder, position, payloads)
        if(position == mDataList.size) return
        if(payloads == null || payloads.size < 1){
            onBindViewHolder(holder, position)
        }
    }

    override fun onBindViewHolder(holder: CommonViewHolder?, position: Int) {
        val t = mDataList.get(position)
        convert(holder!!, position, t)
        holder.itemView.setOnClickListener { v ->
            onItemClickListener!!.onClick(v, position, t)
        }

    }

    override fun getItemCount(): Int {
        return mDataList.size
    }

    override fun getItemViewType(position: Int): Int {
        return super.getItemViewType(position)
    }

    abstract fun convert(holder: CommonViewHolder, position: Int, t: T)

    /***RecyclerView的通用ViewHolder***/
    class CommonViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private var itemViews: SparseArray<View>
        private var convertView: View

        init {
            convertView = view
            itemViews = SparseArray()
        }

        fun <T : View> getView(viewId: Int): T{
            var view = itemViews.get(viewId)
            if(view == null){
                view = convertView.findViewById(viewId)
                itemViews.put(viewId, view)
            }
            return view as T
        }
    }

    /**RecyclerView的点击接口*/
    interface OnRecyclerViewItemClickListener<T> {
        fun onClick(v: View, position: Int, t: T)
    }
}